#include <iostream>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include "Lock.hpp"

using namespace std;

int tickets = 1000;
Mutex mymutex;

bool getTickets()
{
    bool ret = false;
    LockGuard lockGuard(&mymutex);
    if(tickets > 0)
    {
        usleep(10000);
        cout << "thread: " << pthread_self() << " get a ticket: " << tickets << endl;
        tickets--;
        ret = true;
    }

    return ret;
}

void *startRoutine(void *args)
{
    const char *name = static_cast<const char*> (args);
    while(true)
    {
        if(!getTickets())
        {
            break;
        }
        cout << name << "get tickets success" << endl;

        usleep(100);
    }
}

int main()
{
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, nullptr, startRoutine, (void*)"thread 1");
    pthread_create(&t2, nullptr, startRoutine, (void*)"thread 1");
    pthread_create(&t3, nullptr, startRoutine, (void*)"thread 1");
    pthread_create(&t4, nullptr, startRoutine, (void*)"thread 1");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}